package org.snail.transport.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.snail.transport.protocol.Header;
import org.snail.transport.protocol.MessageType;

/**
 * 由客户端发起心跳。
 *
 * @author fish
 */
@ChannelHandler.Sharable
public class ConnectorIdleStateTrigger extends ChannelInboundHandlerAdapter {


    private static final ByteBuf HEARTBEAT_BUF;

    /**
     * 心跳包这里可忽略高地址的4位序列化/反序列化标志
     */
    static {
        ByteBuf buf = Unpooled.buffer(Header.HEAD_LENGTH);
        buf.writeShort(Header.MAGIC);
        buf.writeByte(MessageType.HEARTBEAT);
        buf.writeByte(0);
        buf.writeLong(0);
        buf.writeInt(0);
        HEARTBEAT_BUF = Unpooled.unreleasableBuffer(buf).asReadOnly();
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object event) throws Exception {
        if (event instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) event).state();
            if (state == IdleState.WRITER_IDLE) {
                ctx.writeAndFlush(HEARTBEAT_BUF);
            }
        } else {
            super.userEventTriggered(ctx, event);
        }
    }
}
